﻿using Api.util;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using Domain;
using NHibernate.Transform;

namespace Api
{
   public class BaseService<T>
    {
       private ISessionFactory sessionFactory = SessionFactory.CreateInstance();
      
       /// <summary>
       /// 测试sessionfactory 是否存在
       /// </summary>
       /// <returns></returns>
       public  bool test_session_exit()
       {
           if (sessionFactory == null)
           {
               return false;
           }
           else {
               return true;
           }
       }
       /// <summary>
       /// 根据id 查询
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
       public virtual T find(int id) {
           using (ISession session = sessionFactory.OpenSession())
           {
               using (ITransaction tran = session.BeginTransaction())
               {
                   try
                   {
                       //Persistent
                       return session.Get<T>(id);
                   }
                   catch (Exception ex)
                   {                     
                       throw ex;
                   }
               }
           }
           T result = default(T);
           return result;
       }

       /// <summary>
       /// 根据sql 查询
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
       public virtual T findBySql(string sql) {
           ///使用using 自动释放资源
           using (ISession session = sessionFactory.OpenSession())
           {
               IList<T> list = session.CreateSQLQuery(sql).AddEntity(typeof(T)).List<T>();
               if (list != null&&list.Count>0)
               {
                   return list[0];
               }
               else
               {
                   return default(T);
               }
           }
       }
      
       /// <summary>
       /// 查询一个列表
       /// </summary>
       /// <returns></returns>
       public virtual IList<T> findListBySql(string sql) {

           ///使用using 自动释放资源
           using (ISession session = sessionFactory.OpenSession())
           {
               using (ITransaction tran = session.BeginTransaction())
               {
                   try
                   {
                       IList<T> list = session.CreateQuery(sql).List<T>();
                       if (list != null && list.Count > 0)
                       {
                           return list;
                       }
                       else
                       {
                           return default(IList<T>);
                       }
                   }
                   catch (Exception ex)
                   {
                       tran.Rollback();
                       throw ex;
                   }
               }
           }
       }

       /// <summary>
       /// 通过复杂sql 查询一个级联列表
       /// </summary>
       /// <returns></returns>
       public virtual IList findListByJoinSql(string sql,object[] values)
       {
           ///使用using 自动释放资源
           using (ISession session = sessionFactory.OpenSession())
           {
               using (ITransaction tran = session.BeginTransaction())
               {
                   try
                   {
                       ISQLQuery query = session.CreateSQLQuery(sql);
                       if (values!=null)
                       {
                           for (int i = 0; i < values.Length; i++)
                           {
                               query.SetParameter(i, values[i]);
                           }    
                       }
                       IList list = query.SetResultTransformer(Transformers.AliasToEntityMap).List();
                      return list;
                   }
                   catch (Exception ex)
                   {
                       throw ex;
                   }
               }
           }
       }

       /// <summary>
       /// 查询唯一结果集和  比如 count（id）
       /// </summary>
       /// <param name="sql"></param>
       /// <param name="values"></param>
       /// <returns></returns>
       public virtual object uniqResult(string sql,object[] values) {
           ///使用using 自动释放资源
           using (ISession session = sessionFactory.OpenSession())
           {
               using (ITransaction tran = session.BeginTransaction())
               {
                   try
                   {
                       ISQLQuery query = session.CreateSQLQuery(sql);
                       if (values != null)
                       {
                           for (int i = 0; i < values.Length; i++)
                           {
                               query.SetParameter(i, values[i]);
                           }
                       }
                       return query.UniqueResult();
                   }
                   catch (Exception ex)
                   {
                       throw ex;
                   }
               }
           }
       }


       /// <summary>
       /// 获取卡用户类型
       /// </summary>
       /// <param name="sql"></param>
       /// <param name="values"></param>
       /// <returns></returns>
       public virtual int get_owner_type(string sql)
       {
           ///使用using 自动释放资源
           using (ISession session = sessionFactory.OpenSession())
           {

               try
               {
                   ISQLQuery query = session.CreateSQLQuery(sql);
                   object o=query.UniqueResult();
                   if (o == null || o.ToString() == "") {
                       return 0;
                   }
                   return int.Parse(o.ToString());
               }
               catch (Exception ex)
               {
                   throw ex;
               }              
           }
       }

       /// <summary>
       /// 保存数据 保存成功返回主键id  失败 0
       /// </summary>
       /// <param name="t"></param>
       /// <returns></returns>
       public virtual int save(T t){
           if (t == null)
           {
               return 0;
           }
           else {

               using (ISession session = sessionFactory.OpenSession())
               {
                   using (ITransaction tran = session.BeginTransaction())
                   {
                       try
                       {
                           //Persistent
                           Object i = session.Save(t);
                           tran.Commit();
                           return (int)i;
                       }
                       catch (Exception ex)
                       {
                           tran.Rollback();
                           throw ex;
                       }
                   }
               }
           }
       }
       public virtual bool update(T t) {
           ///使用using 自动释放资源
           using (ISession session = sessionFactory.OpenSession())
           {
               using (ITransaction tran = session.BeginTransaction())
               {                   
                   try
                   {
                       session.Update(t);
                       tran.Commit();
                       return true;
                   }
                   catch (Exception ex)
                   {
                       tran.Rollback();
                       return false;
                       throw ex;
                   }
               }
           }
       }
       /// <summary>
       /// 通过sql 语句修改
       /// </summary>
       /// <param name="sql"></param>
       /// <returns></returns>
       public virtual bool updateBySql(string sql) {

           ///使用using 自动释放资源
           using (ISession session = sessionFactory.OpenSession())
           {
               using (ITransaction tran = session.BeginTransaction())
               {
                   try
                   {
                       session.CreateSQLQuery(sql).ExecuteUpdate();                    
                       tran.Commit();
                       return true;
                   }
                   catch (Exception ex)
                   {
                       tran.Rollback();
                       return false;
                       throw ex;
                   }
               }
           }
       }

       public virtual object uniqResultBySql(string sql)
       {
           ///使用using 自动释放资源
           using (ISession session = sessionFactory.OpenSession())
           {
               using (ITransaction tran = session.BeginTransaction())
               {
                   try
                   {
                       ISQLQuery query = session.CreateSQLQuery(sql);

                       return query.UniqueResult();
                   }
                   catch (Exception ex)
                   {
                       throw ex;
                   }
               }
           }
       }

       /// <summary>
       /// sql 删除
       /// </summary>
       /// <returns></returns>
       public virtual bool deleteBysql(string sql) {
           ///使用using 自动释放资源
           using (ISession session = sessionFactory.OpenSession())
           {
               using (ITransaction tran = session.BeginTransaction())
               {
                   try
                   {
                       session.Delete(sql);
                       tran.Commit();
                       return true;
                   }
                   catch (Exception ex)
                   {
                       tran.Rollback();
                       return false;
                       throw ex;
                   }
               }
           }
       }
    }
}
